<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    
    <title>并发——深入分析ThreadLocal的实现原理 | 博客主页 | 世界是个球，前方总有路！</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="并发">
    <meta name="description" content="一、前言&amp;emsp;&amp;emsp;这篇博客来分析一下ThreadLocal的实现原理以及常见问题，由于现在时间比较晚了，我就不废话了，直接进入正题。   二、正文2.1 ThreadLocal是什么&amp;emsp;&amp;emsp;在讲实现原理之前，我先来简单的说一说ThreadLocal是什么。ThreadLocal被称作线程局部变量，当我们定义了一个ThreadLocal变量，所有的线程共同使用这个变量，">
<meta property="og:type" content="article">
<meta property="og:title" content="并发——深入分析ThreadLocal的实现原理">
<meta property="og:url" content="http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ThreadLocal%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/index.html">
<meta property="og:site_name" content="博客主页">
<meta property="og:description" content="一、前言&amp;emsp;&amp;emsp;这篇博客来分析一下ThreadLocal的实现原理以及常见问题，由于现在时间比较晚了，我就不废话了，直接进入正题。   二、正文2.1 ThreadLocal是什么&amp;emsp;&amp;emsp;在讲实现原理之前，我先来简单的说一说ThreadLocal是什么。ThreadLocal被称作线程局部变量，当我们定义了一个ThreadLocal变量，所有的线程共同使用这个变量，">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-04-15T18:55:26.000Z">
<meta property="article:modified_time" content="2020-04-16T08:36:49.457Z">
<meta property="article:author" content="特务依昂">
<meta property="article:tag" content="并发">
<meta name="twitter:card" content="summary">
    
        <link rel="alternate" type="application/atom+xml" title="博客主页" href="/blog/atom.xml">
    
    <link rel="shortcut icon" href="/blog/img/title.png">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

<meta name="generator" content="Hexo 4.2.0"></head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/blog/img/brand.jpg)">
      <div class="brand">
        <a href="/blog/" class="avatar waves-effect waves-circle waves-light">
          <img src="/blog/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">特务依昂</h5>
          <a href="mailto:1131564805@qq.com" title="1131564805@qq.com" class="mail">1131564805@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/blog/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                博客
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                分类
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/tewuyiang" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://weibo.com/u/5516635708/" target="_blank" >
                <i class="icon icon-lg icon-weibo"></i>
                Weibo
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.cnblogs.com/tuyang1129/" target="_blank" >
                <i class="icon icon-lg icon-link"></i>
                博客园
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">并发——深入分析ThreadLocal的实现原理</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">并发——深入分析ThreadLocal的实现原理</h1>
        <h5 class="subtitle">
            
                <time datetime="2020-04-15T18:55:26.000Z" itemprop="datePublished" class="page-time">
  2020-04-16
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/%E5%B9%B6%E5%8F%91/">并发</a></li></ul>

            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#一、前言"><span class="post-toc-number">1.</span> <span class="post-toc-text">一、前言</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#二、正文"><span class="post-toc-number">2.</span> <span class="post-toc-text">二、正文</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-1-ThreadLocal是什么"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">2.1 ThreadLocal是什么</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-2-ThreadLocal的实现原理"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">2.2 ThreadLocal的实现原理</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-3-ThreadLocal中的get方法"><span class="post-toc-number">2.3.</span> <span class="post-toc-text">2.3 ThreadLocal中的get方法</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-4-ThreadLocal中的set方法"><span class="post-toc-number">2.4.</span> <span class="post-toc-text">2.4 ThreadLocal中的set方法</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-5-ThreadLocalMap的中的弱引用"><span class="post-toc-number">2.5.</span> <span class="post-toc-text">2.5 ThreadLocalMap的中的弱引用</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-6-ThreadLocal造成的内存溢出问题"><span class="post-toc-number">2.6.</span> <span class="post-toc-text">2.6 ThreadLocal造成的内存溢出问题</span></a></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#三、总结"><span class="post-toc-number">3.</span> <span class="post-toc-text">三、总结</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#四、参考"><span class="post-toc-number">4.</span> <span class="post-toc-text">四、参考</span></a></li></ol>
        </nav>
    </aside>


<article id="post-并发——深入分析ThreadLocal的实现原理"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">并发——深入分析ThreadLocal的实现原理</h1>
        <div class="post-meta">
            <time class="post-time" title="2020-04-16 02:55:26" datetime="2020-04-15T18:55:26.000Z"  itemprop="datePublished">2020-04-16</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/%E5%B9%B6%E5%8F%91/">并发</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h1 id="一、前言"><a href="#一、前言" class="headerlink" title="一、前言"></a>一、前言</h1><p>&emsp;&emsp;这篇博客来分析一下<code>ThreadLocal</code>的实现原理以及常见问题，由于现在时间比较晚了，我就不废话了，直接进入正题。</p>
<br>

<h1 id="二、正文"><a href="#二、正文" class="headerlink" title="二、正文"></a>二、正文</h1><h2 id="2-1-ThreadLocal是什么"><a href="#2-1-ThreadLocal是什么" class="headerlink" title="2.1 ThreadLocal是什么"></a>2.1 ThreadLocal是什么</h2><p>&emsp;&emsp;在讲实现原理之前，我先来简单的说一说<code>ThreadLocal</code>是什么。<code>ThreadLocal</code>被称作<strong>线程局部变量</strong>，当我们定义了一个<code>ThreadLocal</code>变量，所有的线程共同使用这个变量，但是对于每一个线程来说，实际操作的值是互相独立的。简单来说就是，<strong>ThreadLocal能让线程拥有自己内部独享的变量</strong>。举一个简单的例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 定义一个线程共享的ThreadLocal变量</span></span><br><span class="line"><span class="keyword">static</span> ThreadLocal&lt;Integer&gt; tl = <span class="keyword">new</span> ThreadLocal&lt;&gt;();</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 创建第一个线程</span></span><br><span class="line">    Thread t1 = <span class="keyword">new</span> Thread(() -&gt; &#123;</span><br><span class="line">        <span class="comment">// 设置ThreadLocal变量的初始值，为1</span></span><br><span class="line">        tl.set(<span class="number">1</span>);</span><br><span class="line">        <span class="comment">// 循环打印ThreadLocal变量的值</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"----"</span> + tl.get());</span><br><span class="line">            <span class="comment">// 每次打印完让值 + 1</span></span><br><span class="line">            tl.set(tl.get() + <span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, <span class="string">"thread1"</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 创建第二个线程</span></span><br><span class="line">    Thread t2 = <span class="keyword">new</span> Thread(() -&gt; &#123;</span><br><span class="line">         <span class="comment">// 设置ThreadLocal变量的初始值，为100，与上一个线程区别开</span></span><br><span class="line">        tl.set(<span class="number">100</span>);</span><br><span class="line">        <span class="comment">// 循环打印ThreadLocal变量的值</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"----"</span> + tl.get());</span><br><span class="line">            <span class="comment">// 每次打印完让值 - 1</span></span><br><span class="line">            tl.set(tl.get() - <span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, <span class="string">"thread2"</span>);</span><br><span class="line">	<span class="comment">// 开启两个线程</span></span><br><span class="line">    t1.start();</span><br><span class="line">    t2.start();</span><br><span class="line">    </span><br><span class="line">    tl.remove();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;上面的代码，运行结果如下（注：每次运行的结果可能不同）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">thread1----<span class="number">1</span></span><br><span class="line">thread2----<span class="number">100</span></span><br><span class="line">thread1----<span class="number">2</span></span><br><span class="line">thread2----<span class="number">99</span></span><br><span class="line">thread1----<span class="number">3</span></span><br><span class="line">thread2----<span class="number">98</span></span><br><span class="line">thread1----<span class="number">4</span></span><br><span class="line">thread2----<span class="number">97</span></span><br><span class="line">thread1----<span class="number">5</span></span><br><span class="line">thread2----<span class="number">96</span></span><br><span class="line">thread1----<span class="number">6</span></span><br><span class="line">thread2----<span class="number">95</span></span><br><span class="line">thread1----<span class="number">7</span></span><br><span class="line">thread2----<span class="number">94</span></span><br><span class="line">thread1----<span class="number">8</span></span><br><span class="line">thread2----<span class="number">93</span></span><br><span class="line">thread1----<span class="number">9</span></span><br><span class="line">thread2----<span class="number">92</span></span><br><span class="line">thread1----<span class="number">10</span></span><br><span class="line">thread2----<span class="number">91</span></span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;通过上面的输出结果我们可以发现，<code>线程1</code>和<code>线程2</code>虽然使用的是同一个<code>ThreadLocal</code>变量存储值，但是输出结果中，两个线程的值却互不影响，<code>线程1</code>从<code>1</code>输出到<code>10</code>，而<code>线程2</code>从<code>100</code>输出到<code>91</code>。这就是<code>ThreadLocal</code>的功能，即让每一个线程拥有自己独立的变量，多个线程之间互不影响。</p>
<br>

<h2 id="2-2-ThreadLocal的实现原理"><a href="#2-2-ThreadLocal的实现原理" class="headerlink" title="2.2 ThreadLocal的实现原理"></a>2.2 ThreadLocal的实现原理</h2><p>&emsp;&emsp;下面我就就来说一说<code>ThreadLocal</code>是如何做到线程之间相互独立的，也就是它的实现原理。这里我直接放出结论，后面再根据源码分析：<strong>每一个线程都有一个对应的Thread对象，而Thread类有一个成员变量，它是一个Map集合，这个Map集合的key就是ThreadLocal的引用，而value就是当前线程在key所对应的ThreadLocal中存储的值。当某个线程需要获取存储在ThreadLocal变量中的值时，ThreadLocal底层会获取当前线程的Thread对象中的Map集合，然后以ThreadLocal作为key，从Map集合中查找value值</strong>。这就是<code>ThreadLocal</code>实现线程独立的原理。也就是说，<code>ThreadLocal</code>能够做到线程独立，是因为值并不存在<code>ThreadLocal</code>中，而是存储在线程对象中。下面我们根据<code>ThreadLocal</code>中两个最重要的方法来确认这一点。</p>
<br>

<h2 id="2-3-ThreadLocal中的get方法"><a href="#2-3-ThreadLocal中的get方法" class="headerlink" title="2.3 ThreadLocal中的get方法"></a>2.3 ThreadLocal中的get方法</h2><p>&emsp;&emsp;<code>get</code>方法的作用非常简单，就是线程向<code>ThreadLocal</code>中取值，下面我们来看看它的源码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> T <span class="title">get</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取当前线程的Thread对象</span></span><br><span class="line">    Thread t = Thread.currentThread();</span><br><span class="line">    <span class="comment">// getMap方法传入Thread对象，此方法将返回Thread对象中存储的一个Map集合</span></span><br><span class="line">    <span class="comment">// 这个Map集合的类型为ThreadLocalMap，这是ThreadLoacl的一个内部类</span></span><br><span class="line">    <span class="comment">// 当前线程存放在ThreadLocal中的值，实际上存放在这个Map集合中</span></span><br><span class="line">    ThreadLocalMap map = getMap(t);</span><br><span class="line">    <span class="comment">// 如果当前Map集合已经初始化，则直接从Map集合中查找</span></span><br><span class="line">    <span class="keyword">if</span> (map != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// ThreadLocalMap的key其实就是ThreadLoacl对象的引用</span></span><br><span class="line">        <span class="comment">// 所以要找到线程在当前ThreadLoacl中存放的值，就需要以当前ThreadLoacl作为key</span></span><br><span class="line">        <span class="comment">// getEntry方法就是通过key获取map中的一个key-value，而这里使用的key就是this</span></span><br><span class="line">        ThreadLocalMap.Entry e = map.getEntry(<span class="keyword">this</span>);</span><br><span class="line">        <span class="comment">// 如果返回值不为空，表示查找成功</span></span><br><span class="line">        <span class="keyword">if</span> (e != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">            <span class="comment">// 于是获取对应的value并返回</span></span><br><span class="line">            T result = (T)e.value;</span><br><span class="line">            <span class="keyword">return</span> result;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 若当前线程的ThreadLocalMap还未初始化，或者查找失败，则调用以下方法</span></span><br><span class="line">    <span class="keyword">return</span> setInitialValue();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> T <span class="title">setInitialValue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 此方法默认返回null，但是可以由子类进行重新，根据需求返回需要的值</span></span><br><span class="line">    T value = initialValue();</span><br><span class="line">    <span class="comment">// 获取当前线程的Thread对象</span></span><br><span class="line">    Thread t = Thread.currentThread();</span><br><span class="line">    <span class="comment">// 获取对应的ThreadLocalMap</span></span><br><span class="line">    ThreadLocalMap map = getMap(t);</span><br><span class="line">    <span class="comment">// 如果Map已经初始化了，就直接往map中加入一个key-value</span></span><br><span class="line">    <span class="comment">// key就是当前ThreadLocal对象的引用，而value就是上面获取到的value，默认为null</span></span><br><span class="line">    <span class="keyword">if</span> (map != <span class="keyword">null</span>)</span><br><span class="line">        map.set(<span class="keyword">this</span>, value);</span><br><span class="line">    <span class="comment">// 若还没有初始化，则调用createMap创建ThreadLocalMap对象</span></span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        createMap(t, value);</span><br><span class="line">    <span class="comment">// 返回initialValue方法返回的值，默认为null</span></span><br><span class="line">    <span class="keyword">return</span> value;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">createMap</span><span class="params">(Thread t, T firstValue)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 创建ThreadLocalMap对象，构造方法传入的是第一对放入其中的key-value</span></span><br><span class="line">    <span class="comment">// 这个key也就是当前线程第一次调用get方法的ThreadLocal对象，也就是当前ThreadLocal对象</span></span><br><span class="line">    <span class="comment">// 而firstValue则是initialValue方法的返回值，默认为null</span></span><br><span class="line">    t.threadLocals = <span class="keyword">new</span> ThreadLocalMap(<span class="keyword">this</span>, firstValue);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;上面的代码非常直观的验证了我之前说过的<code>ThreadLocal</code>的实现原理。通过上面的代码，我们可以非常直观的看到，线程向<code>ThreadLocal</code>中存放的值，最后都放入了线程自己的<code>ThreadLocalMap</code>中，而这个<code>map</code>的<code>key</code>就是当前<code>ThreadLocal</code>的引用。而<code>ThreadLocal</code>中，获取线程的<code>ThreadLocalMap</code>的方法<code>getMap</code>的代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">ThreadLocalMap <span class="title">getMap</span><span class="params">(Thread t)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 直接返回Thread对象的threadLocals成员变量</span></span><br><span class="line">    <span class="keyword">return</span> t.threadLocals;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;我们再看看<code>Thread</code>类中的<code>threadLocals</code>变量：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 可以看到，ThreadLocalMap是ThreadLocal的内部类 */</span></span><br><span class="line">ThreadLocal.ThreadLocalMap threadLocals = <span class="keyword">null</span>;</span><br></pre></td></tr></table></figure>

<br>

<h2 id="2-4-ThreadLocal中的set方法"><a href="#2-4-ThreadLocal中的set方法" class="headerlink" title="2.4 ThreadLocal中的set方法"></a>2.4 ThreadLocal中的set方法</h2><p>&emsp;&emsp;下面再来看一看<code>ThreadLocal</code>的<code>set</code>方法的实现，<code>set</code>方法用来使线程向<code>ThreadLocal</code>中存放值（实际上是存放在线程自己的<code>Map</code>中）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">set</span><span class="params">(T value)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取当前线程的Thread对象</span></span><br><span class="line">    Thread t = Thread.currentThread();</span><br><span class="line">    <span class="comment">// 获取当前线程的ThreadLocalMap</span></span><br><span class="line">    ThreadLocalMap map = getMap(t);</span><br><span class="line">    <span class="comment">// 若map已经初始化，则之际将value放入Map中，对应的key就是当前ThreadLocal的引用</span></span><br><span class="line">    <span class="keyword">if</span> (map != <span class="keyword">null</span>)</span><br><span class="line">        map.set(<span class="keyword">this</span>, value);</span><br><span class="line">    <span class="comment">// 若没有初始化，则调用createMap方法，为当前线程t创建ThreadLocalMap，</span></span><br><span class="line">    <span class="comment">// 然后将key-value放入（此方法已经在上面讲解get方法是看过）</span></span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        createMap(t, value);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;这就是<code>set</code>方法的实现，比较简单。看完上面两个关键方法的实现，相信大家对<code>ThreadLocal</code>的实现已经有了一个比较清晰的认识，下面我们来更加深入的分析<code>ThreadLocal</code>，看看<code>ThreadLocalMap</code>的一些实现细节。</p>
<br>

<h2 id="2-5-ThreadLocalMap的中的弱引用"><a href="#2-5-ThreadLocalMap的中的弱引用" class="headerlink" title="2.5 ThreadLocalMap的中的弱引用"></a>2.5 ThreadLocalMap的中的弱引用</h2><p>&emsp;&emsp;<code>ThreadLocalMap</code>的实现其实就是一个比较普通的<code>Map</code>集合，它的实现和<code>HashMap</code>类似，所以具体的实现细节我们就不一一讲解了，这里我们只关注它最特别的一个地方，即它内部的节点<code>Entry</code>。我们先来看看<code>Entry</code>的代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Entry是ThreadLocalMap的内部类，表示Map的节点</span></span><br><span class="line"><span class="comment">// 这里继承了WeakReference，这是java实现的弱引用类，泛型为ThreadLocal</span></span><br><span class="line"><span class="comment">// 表示在这个Map中，作为key的ThreadLocal是弱引用</span></span><br><span class="line"><span class="comment">// （这里value是强引用，因为没用WeakReference）</span></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Entry</span> <span class="keyword">extends</span> <span class="title">WeakReference</span>&lt;<span class="title">ThreadLocal</span>&lt;?&gt;&gt; </span>&#123;</span><br><span class="line">    <span class="comment">/** 存储value */</span></span><br><span class="line">    Object value;</span><br><span class="line"></span><br><span class="line">    Entry(ThreadLocal&lt;?&gt; k, Object v) &#123;</span><br><span class="line">        <span class="comment">// 将key的值传入父类WeakReference的构造方法，用弱引用来引用key</span></span><br><span class="line">        <span class="keyword">super</span>(k);</span><br><span class="line">        <span class="comment">// value则直接使用上面的强引用</span></span><br><span class="line">        value = v;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;可以看到，上面的<code>Entry</code>比较特殊，它继承自<code>WeakReference</code>类型，这是<code>Java</code>实现的弱引用。在具体讲解前，我们先来介绍一下不同类型的引用：</p>
<blockquote>
<p><strong>强引用</strong>：这是Java中最常见的引用，在没有使用特殊引用的情况下，都是强引用，比如Object o = new Object()就是典型的强引用。能让程序员通过强引用访问到的对象，不会被JVM垃圾回收，即使内存空间不够，JVM也不会回收这些对象，而是抛出内存溢出异常；</p>
<p><strong>软引用</strong>：软引用描述的是一些还有用，但不是必须的对象。被软引用所引用的对象，也不会被垃圾回收，直到JVM将要发生内存溢出异常时，才会将这些对象列为回收对象，进行回收。在JDK1.2之后，提供了SoftReference类实现软引用；</p>
<p><strong>弱引用</strong>：弱引用描述的是非必须的对象，被弱引用所引用的对象，只能生存到下一次垃圾回收前，下一次垃圾回收来临，此对象就会被回收。在JDK1.2之后，提供了WeakReference类实现弱引用（也就是上面Entry继承的类）；</p>
<p><strong>虚引用</strong>：这是最弱的一种引用关系，一个对象是否有虚引用，完全不会对其生存时间产生影响，我们也不能通过一个虚引用访问对象，使用虚引用的唯一目的就是，能在这个对象被回收时，受到一个系统的通知。JDK1.2之后，提供了PhantomReference实现虚引用；</p>
</blockquote>
<p>&emsp;&emsp;介绍完各类引用的概念，我们就可以来分析一下<code>Entry</code>为什么需要继承<code>WeakReference</code>类了。从代码中，我们可以看到，<code>Entry</code>将<code>key</code>值，也就是<code>ThreadLocal</code>的引用传入到了<code>WeakReference</code>的构造方法中，也就是说在<code>ThreadLocalMap</code>中，<code>key</code>的引用是弱引用。这表明，当没有其他强引用指向<code>key</code>时，这个<code>key</code>将会在下一次垃圾回收时被<code>JVM</code>回收。</p>
<p>&emsp;&emsp;为什么需要这么做呢？这么做的目的自然是为了有利于垃圾回收了。如果了解过<code>JVM</code>的垃圾回收算法的应该知道，<code>JVM</code>判断一个对象是否需要被回收，判断的依据是这个对象还能否被我们所使用，举个简单的例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    Object o = <span class="keyword">new</span> Object();</span><br><span class="line">    o = <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;上面的代码中，我们创建了一个对象，并使用强引用<code>o</code>指向它，然后我们将<code>o</code>置为空，这个时候刚刚创建的对象就丢失了，因为我们无法通过任何引用找到这个对象，从而使用它，于是这个对象就需要被回收，这种判断依据被称为<strong>可达性分析</strong>。关于<code>JVM</code>的垃圾回收算法，可以参考这篇博客：<a href="https://www.cnblogs.com/tuyang1129/p/12508216.html" target="_blank" rel="noopener">Java中的垃圾回收算法详解</a>。</p>
<p>&emsp;&emsp;好，回归正题，我们开始分析为什么<code>ThreadLocalMap</code>需要让<code>key</code>使用弱引用。假设我们创建了一个<code>ThreadLocal</code>，使用完之后没有用了，我们希望能够让它被<code>JVM</code>回收，于是有了下面这个过程：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建ThreadLocal对象</span></span><br><span class="line">ThreadLocal tl = <span class="keyword">new</span> ThreadLocal();</span><br><span class="line"></span><br><span class="line"><span class="comment">// .....省略使用的过程...</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用完成，希望被JVM回收，于是执行以下操作，解除强引用</span></span><br><span class="line">tl = <span class="keyword">null</span>;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;我们在使用完<code>ThreadLocal</code>之后，解除对它的强引用，希望它被<code>JVM</code>回收。但是<code>JVM</code>无法回收它，因为我们虽然在此处释放了对它的强引用，但是它还有其它强引用，那就是<code>Thread</code>对象的<code>ThreadLocalMap</code>的<code>key</code>。我们之前反复说过，<code>ThreadLocalMap</code>的<code>key</code>就是<code>ThreadLocal</code>对象的引用，若这个引用是一个强引用，那么在当前线程执行完毕，被回收前，<code>ThreadLocalMap</code>不会被回收，而<code>ThreadLocalMap</code>不会被回收，它的<code>key</code>引用的<code>ThreadLocal</code>也就不会回收，这就是问题的所在。而<strong>使用弱引用就可以保证，在其他对ThreadLocal的强引用解除后，ThreadLocalMap对它的引用不会影响JVM对它进行垃圾回收</strong>。这就是使用弱引用的原因。</p>
<br>

<h2 id="2-6-ThreadLocal造成的内存溢出问题"><a href="#2-6-ThreadLocal造成的内存溢出问题" class="headerlink" title="2.6 ThreadLocal造成的内存溢出问题"></a>2.6 ThreadLocal造成的内存溢出问题</h2><p>&emsp;&emsp;上面描述了对<code>ThreadLocalMap</code>对<code>key</code>使用弱引用，来避免<code>JVM</code>无法回收<code>ThreadLocal</code>的问题，但是这里却还有另外一个问题。我们看上面<code>Entry</code>的代码发现，<code>key</code>值虽然使用的弱引用，但是<strong>value使用的却是强引用</strong>。这会造成一个什么问题？<strong>这会造成key被JVM回收，但是value却无法被收，key对应的ThreadLocal被回收后，key变为了null，但是value却还是原来的value，因为被ThreadLocalMap所引用，将无法被JVM回收</strong>。若<code>value</code>所占内存较大，线程较多的情况下，将持续占用大量内存，甚至造成内存溢出。我们通过一段代码演示这个问题：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Main</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 循环创建多个TestClass</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line">            <span class="comment">// 创建TestClass对象</span></span><br><span class="line">            TestClass t = <span class="keyword">new</span> TestClass(i);</span><br><span class="line">            <span class="comment">// 调用反复</span></span><br><span class="line">            t.printId();</span><br><span class="line">            <span class="comment">// *************注意此处，非常关键：为了帮助回收，将t置为null</span></span><br><span class="line">            t = <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">TestClass</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> id;</span><br><span class="line">        <span class="comment">// 每个TestClass对象对应一个很大的数组</span></span><br><span class="line">        <span class="keyword">int</span>[] arr = <span class="keyword">new</span> <span class="keyword">int</span>[<span class="number">100000000</span>];</span><br><span class="line">        <span class="comment">// 每个TestClass对象对应一个ThreadLocal对象</span></span><br><span class="line">        ThreadLocal&lt;<span class="keyword">int</span>[]&gt; threadLocal = <span class="keyword">new</span> ThreadLocal&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        TestClass(<span class="keyword">int</span> id) &#123;</span><br><span class="line">            <span class="keyword">this</span>.id = id;</span><br><span class="line">            <span class="comment">// threadLocal存放的就是这个很大的数组</span></span><br><span class="line">            threadLocal.set(arr);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">printId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(id);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;上面的代码多次创建所占内存非常大的对象，并在创建后，立即解除对象的强引用，让对象可以被<code>JVM</code>回收。按道理来说，上面的代码运行应该不会发生内存溢出，因为我们虽然创建了多个大对象，占用了大量空间，但是这些对象立即就用不到了，可以被垃圾回收，而这个对象被垃圾回收后，对象的<code>id</code>，数组，和<code>threadLocal</code>成员都会被回收，所以所占内存不会持续升高，但是实际运行结果如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">0</span></span><br><span class="line"><span class="number">1</span></span><br><span class="line"><span class="number">2</span></span><br><span class="line">Exception in thread <span class="string">"main"</span> java.lang.OutOfMemoryError: Java heap space</span><br><span class="line">	at Main$TestClass.&lt;init&gt;(Main.java:<span class="number">23</span>)</span><br><span class="line">	at Main.main(Main.java:<span class="number">10</span>)</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;可以看到，很快就发生了内存溢出异常。为什么呢？需要注意到，在<code>TestClass</code>的构造方法中，我们将数组<code>arr</code>放入了<code>ThreadLocal</code>对象中，也就是被放进了当前线程的<code>ThreadLocalMap</code>中，作为<code>value</code>存在。我们前面说过，<code>ThreadLocalMap</code>的<code>value</code>是强引用，这也就意味着虽然<code>ThreadLocal</code>可以被正常回收，但是作为<code>value</code>的大数组无法被回收，因为它仍然被<code>ThreadLocalMap</code>的强引用所指向。于是<code>TestClass</code>对象的超大数组就一种在内存中，占据大量空间，我们连续创建了多个<code>TestClass</code>，内存很快就被占满了，于是发生了内存溢出。而<code>JDK</code>的开发人员自然发现了这个问题，于是有了下面这个解决方案：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Main</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line">            TestClass t = <span class="keyword">new</span> TestClass(i);</span><br><span class="line">            t.printId();</span><br><span class="line">            <span class="comment">// **********注意，与上面的代码只有此处不同************</span></span><br><span class="line">            <span class="comment">// 此处调用了ThreadLocal对象的remove方法</span></span><br><span class="line">            t.threadLocal.remove();</span><br><span class="line">            t = <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">TestClass</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> id;</span><br><span class="line">        <span class="keyword">int</span>[] arr;</span><br><span class="line">        ThreadLocal&lt;<span class="keyword">int</span>[]&gt; threadLocal;</span><br><span class="line"></span><br><span class="line">        TestClass(<span class="keyword">int</span> id) &#123;</span><br><span class="line">            <span class="keyword">this</span>.id = id;</span><br><span class="line">            arr = <span class="keyword">new</span> <span class="keyword">int</span>[<span class="number">100000000</span>];</span><br><span class="line">            threadLocal = <span class="keyword">new</span> ThreadLocal&lt;&gt;();</span><br><span class="line">            threadLocal.set(arr);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">printId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(id);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;上面的代码中，我们在将<code>t</code>置为空时，先调用了<code>ThreadLocal</code>对象的<code>remove</code>方法，这样做了之后，再看看运行结果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">0</span></span><br><span class="line"><span class="number">1</span></span><br><span class="line"><span class="number">2</span></span><br><span class="line"><span class="comment">// ....神略中间部分</span></span><br><span class="line"><span class="number">98</span></span><br><span class="line"><span class="number">99</span></span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;做了上面的修改后，没有再发生内存溢出异常，程序正常执行完毕。这是为什么呢？<code>ThreadLocal</code>的<code>remove</code>方法究竟有什么作用。其实<code>remove</code>方法的作用非常简单，执行<code>remove</code>方法时，会从当前线程的<code>ThreadLocalMap</code>中删除<code>key</code>为当前<code>ThreadLocal</code>的那一个记录，<code>key</code>和<code>value</code>都会被置为null，这样一来，就解除了<code>ThreadLocalMap</code>对<code>value</code>的强引用，使得<code>value</code>可以正常地被<code>JVM</code>回收了。所以，今后如果我们确认不再使用的<code>ThreadLocal</code>对象，一定要记得调用它的<code>remove</code>方法。</p>
<p>&emsp;&emsp;我们之前说过，如果我们没有调用<code>remove</code>方法，那就会导致<code>ThreadLocal</code>在使用完毕后，被正常回收，但是<code>ThreadLocalMap</code>中存放的<code>value</code>无法被回收，此时将会在<code>ThreadLocalMap</code>中出现<code>key</code>为<code>null</code>，而<code>value</code>不为<code>null</code>的元素。为了减少已经无用的对象依旧占用内存的现象，<code>ThreadLocal</code>底层实现中，在操作<code>ThreadLocalMap</code>的过程中，线程若检测到<code>key</code>为<code>null</code>的元素，会将此元素的<code>value</code>置为<code>null</code>，然后将这个元素从<code>ThreadLocalMap</code>中删除，占用的内存就可以让<code>JVM</code>将其回收。比如说在<code>getEntry</code>方法中，或者是<code>Map</code>扩容的方法中等。</p>
<br>

<h1 id="三、总结"><a href="#三、总结" class="headerlink" title="三、总结"></a>三、总结</h1><p>&emsp;&emsp;<code>ThreadLocal</code>实现线程独立的方式是直接将值存放在<code>Thread</code>对象的<code>ThreadLocalMap</code>中，<code>Map</code>的<code>key</code>就是<code>ThreadLocal</code>的引用，且为了有助于<code>JVM</code>进行垃圾回收，<code>key</code>使用的是弱引用。在使用<code>ThreadLocal</code>后，一定要记得调用<code>remove</code>方法，有助于<code>JVM</code>对<code>value</code>的回收。</p>
<br>

<h1 id="四、参考"><a href="#四、参考" class="headerlink" title="四、参考"></a>四、参考</h1><ul>
<li>《深入理解Java虚拟机（第二版）》</li>
<li><a href="https://mp.weixin.qq.com/s/Y24LQwukYwXueTS6NG2kKA" target="_blank" rel="noopener">https://mp.weixin.qq.com/s/Y24LQwukYwXueTS6NG2kKA</a></li>
</ul>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2020-04-16T08:36:49.457Z" itemprop="dateUpdated">2020-04-16 16:36:49</time>
</span><br>


        
        世界是个球，前方总有路！
        
    </div>
    
    <footer>
        <a href="http://tewuyiang.gitee.io/blog">
            <img src="/blog/img/avatar.jpg" alt="特务依昂">
            特务依昂
        </a>
    </footer>
</blockquote>

        


        <div class="post-footer">
            
	<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/blog/tags/%E5%B9%B6%E5%8F%91/" rel="tag">并发</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ThreadLocal%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&title=《并发——深入分析ThreadLocal的实现原理》 — 博客主页&pic=http://tewuyiang.gitee.io/blog/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ThreadLocal%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&title=《并发——深入分析ThreadLocal的实现原理》 — 博客主页&source=一个未来程序员的博客~~~" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ThreadLocal%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《并发——深入分析ThreadLocal的实现原理》 — 博客主页&url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ThreadLocal%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&via=http://tewuyiang.gitee.io/blog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ThreadLocal%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/blog/%E6%98%A5%E6%8B%9B%E9%9D%A2%E7%BB%8F%E2%80%94%E2%80%94%E7%BD%91%E6%98%93%E4%BA%92%E5%A8%B1%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%BC%80%E5%8F%91%E4%B8%80%E9%9D%A2/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">春招面经——网易互娱服务端开发一面</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90CountDownLatch%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">并发——深入分析CountDownLatch的实现原理</h4>
      </a>
    </div>
  
</nav>



    




















</article>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/blog/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>特务依昂 &copy; 2015 - 2020</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ThreadLocal%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&title=《并发——深入分析ThreadLocal的实现原理》 — 博客主页&pic=http://tewuyiang.gitee.io/blog/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ThreadLocal%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&title=《并发——深入分析ThreadLocal的实现原理》 — 博客主页&source=一个未来程序员的博客~~~" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ThreadLocal%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《并发——深入分析ThreadLocal的实现原理》 — 博客主页&url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ThreadLocal%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/&via=http://tewuyiang.gitee.io/blog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://tewuyiang.gitee.io/blog/%E5%B9%B6%E5%8F%91%E2%80%94%E2%80%94%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90ThreadLocal%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/blog/', SHARE: true, REWARD: false };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '人呢，怎么不见了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!欢迎回来!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
